package main.Parallel;

import java.util.Queue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.logging.Level;
import java.util.logging.Logger;

public class OperationQueue extends Thread {
    private Queue<OperationQueueJob> jobs;
    private final Object queueLock = new Object();
    private boolean done = false;
    
    public OperationQueue() {
        this.jobs = new LinkedBlockingDeque<OperationQueueJob>();
    }
    
    public void addJob(OperationQueueJob job) {
        jobs.add(job);
        synchronized (queueLock) {
            queueLock.notify();
        }
    }
    
    @Override
    public void run() {
        while(!done) {
            if(!this.jobs.isEmpty()) {
                OperationQueueJob job = jobs.remove();
                job.run();
            }
            else {
                synchronized (queueLock) {
                    try {
                        queueLock.wait();
                    } catch (InterruptedException ex) {
                        Logger.getLogger(OperationQueue.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        }
    }
    
    public void shutdownWhenDone() {
        done = true;
    }
}
